package com.abl.common.mybatis;

import com.abl.common.util.DBKit;
import com.abl.common.util.SystemKit;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Generator {
    private static final String url = "jdbc:p6spy:mysql://127.0.0.1:3306/abl?serverTimezone=Asia/Shanghai&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useUnicode=true&useSSL=false&useTimezone=false&allowPublicKeyRetrieval=true";
    private static final String username = "root";
    private static final String password = "1234qwer";
    private static final String packageName = "com.abl";
    private static final String moduleName = "domain";
    private static final String entity = "po";
    private static final String xml = "xml";
    private static final String outputDir = "C://generator";

    public static void main(String[] args) throws Exception {
        createPO();
        createTableJavaFile();
    }

    //
    private static void createPO() {
        FastAutoGenerator.create(url, username, password)
                .globalConfig(builder -> {
                    builder.author("") // 设置作者
                            .outputDir(outputDir); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent(packageName) // 设置父包名
                            .moduleName(moduleName) // 设置父包模块名
                            .entity(entity)
                            .pathInfo(Collections.singletonMap(OutputFile.xml, outputDir + File.separator + xml)); // 设置mapperXml生成路径
                })
                // 策略配置
                .strategyConfig(builder -> {
                    builder.addInclude() // 设置需要生成的表名
                            .addTablePrefix()// 设置过滤表前缀
                            .entityBuilder().enableLombok().enableFileOverride().naming(NamingStrategy.underline_to_camel).columnNaming(NamingStrategy.no_change);
                })
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

    //生成Table类
    public static void createTableJavaFile() throws Exception {
        //1，创建FreeMarker的配置类
        Configuration conf = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        conf.setDefaultEncoding(ConstVal.UTF8);
        conf.setClassForTemplateLoading(FreemarkerTemplateEngine.class, StringPool.SLASH);

        //2，指定模板加载器，将模板加入缓存中
        //文件路径加载器，获取到templates文件的路径
        String templatePath = Generator.class.getClassLoader().getResource("template").getPath();
        System.out.println("templatePath: " + templatePath);
        FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(templatePath));
        conf.setTemplateLoader(fileTemplateLoader);

        //3，获取模板
        Template template = conf.getTemplate("Table.java.ftl");

        //4，构造数据模型
        List<HashMap<String, String>> tables = DBKit.getTables(DBKit.getConnection(url, username, password));
        Map<String, Object> map = new HashMap<>();
        map.put("tables", tables);
        map.put("package", packageName + "." + moduleName + "." + entity);


        //5，文件输出
        /**
         * 处理模型
         *      参数一 数据模型
         *      参数二 writer对象（FileWriter（文件输出），printWriter（控制台输出））
         */
        File dir = new File(outputDir);
        File file = new File(outputDir + File.separator + "Table.java");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        file.deleteOnExit();
        template.process(map, new FileWriter(file));
        SystemKit.openDir(outputDir);
//        template.process(map, new FileWriter(outputDir + File.separator + "Table.java"));

    }

}
